/*
 * @Date: 2021-11-21 16:55:09
 * @LastEditors: xiaolan
 * @LastEditTime: 2021-12-08 19:02:11
 * @FilePath: \pms\web\notice\publish.js
 */
let noticeCURD = {
  user_role: sessionStorage.getItem('user_role'),
  user_id: sessionStorage.getItem('user_id'),
  // 个性化显示页面
  showPage() {
    let user_manage = document.getElementById('user_manage')
    let project_manage = document.getElementById('project_manage')
    let money = document.getElementById('money')
    let contract = document.getElementById('contract')
    if (this.user_role == '组员') {
      user_manage.style.display = 'none'
      project_manage.style.display = 'none'
      money.style.display = 'none'
      contract.style.display = 'none'
    }
  },

  // 显示通知信息
  showDataTable() {
    $('.datatable').dataTable({
      autoWidth: true,
      paging: true,
      searching: true,
      aaSorting: [], //不让其按第一列排序
      oLanguage: {
        aria: {
          sortAscending: ': activate to sort column ascending',
          sortDescending: ': activate to sort column descending',
        },
        sProcessing: '处理中...',
        sLengthMenu: '_MENU_ 记录/页',
        sZeroRecords: '没有匹配的记录',
        sInfo: '显示第 _START_ 至 _END_ 项记录，共 _TOTAL_ 项',
        sInfoEmpty: '显示第 0 至 0 项记录，共 0 项',
        sInfoFiltered: '(由 _MAX_ 项记录过滤)',
        sInfoPostFix: '',
        sSearch: '请输入查询信息:',
        oPaginate: {
          sFirst: '首页',
          sPrevious: '上页',
          sNext: '下页',
          sLast: '末页',
        },
      },
      // "aoColumnDefs": [{"bSearchable": false,"bVisible":false,"aTargets":[0]}],
      aoColumns: [
        {
          mRender: function (data, type, full) {
            sReturn = full.id
            return sReturn
          },
          orderable: false,
        },
        {
          mRender: function (data, type, full) {
            sReturn = full.publisherName
            return sReturn
          },
          orderable: true,
        },
        {
          mRender: function (data, type, full) {
            sReturn = full.title
            return sReturn
          },
          orderable: false,
        },
        {
          mRender: function (data, type, full) {
            sReturn = full.content
            return sReturn
          },
          orderable: false,
        },
        {
          mRender: function (data, type, full) {
            sReturn = full.time
            return sReturn
          },
          orderable: false,
        },
        {
          mRender: function (data, type, full) {
            sReturn =
              '<button class="btn btn-xs btn-primary" onclick="noticeCURD.editNoticeInfo(this)">编辑</button>    <button class="btn btn-xs btn-danger" onclick = "noticeCURD.delNoticeInfo(this)">删除</button>'
            return sReturn
          },
          orderable: false,
        },
      ],
      aLengthMenu: [
        [5, 10, 15, 20, 25, 40, 50, -1],
        [5, 10, 15, 20, 25, 40, 50, '所有记录'],
      ],
      fnDrawCallback: function () {
        $('.checkboxes').uniform()
        $('.groupDao.java-checkable').uniform()
      },

      ajax: {
        async: false,
        url: '../project/notice',
        type: 'POST',
        data: {
          action: 'query',
          role: this.user_role,
          id: this.user_id,
        },
        dataSrc: function (result) {
          return result.list
        },
      },
    })
    $('.datatable')
      .find('.groupDao.java-checkable')
      .change(function () {
        var set = jQuery(this).attr('data-set')
        var checked = jQuery(this).is(':checked')
        jQuery(set).each(function () {
          if (checked) {
            $(this).attr('checked', true)
            $(this).parents('tr').addClass('active')
          } else {
            $(this).attr('checked', false)
            $(this).parents('tr').removeClass('active')
          }
        })
        jQuery.uniform.update(set)
      })
    $('.datatable').on('change', 'tbody tr .checkboxes', function () {
      $(this).parents('tr').toggleClass('active')
    })
  },

  //删除通知信息
  delNoticeInfo(delbtn) {
    let action = 'delete'
    if (confirm('你确定要删除这条信息嘛？')) {
      let id = delbtn.parentElement.parentElement.firstElementChild.innerHTML
      $.ajax({
        async: true,
        type: 'POST',
        url: '../project/notice',
        data: {
          id,
          notice: id,
          action,
        },
        success: function (data) {
          alert('删除成功')
          location.reload()
        },
        error: function () {
          alert('删除失败，请重试！！！')
        },
      })
    }
  },

  // 编辑通知信息
  editNoticeInfo(editbtn) {
    let action = 'edit'
    let id = ''
    $('#notice_edit_form').modal('show')
    let trID = editbtn.parentElement.parentElement.firstElementChild
    id = trID.innerHTML
    let notice = id
    document.querySelector('#edit_publisherName').value =
      trID.nextElementSibling.innerHTML
    document.querySelector('#edit_noticeTitle').value =
      trID.nextElementSibling.nextElementSibling.innerHTML
    document.querySelector('#edit_noticeContent').innerHTML =
      trID.nextElementSibling.nextElementSibling.nextElementSibling.innerHTML
    document
      .querySelector('#edit_submit_button')
      .addEventListener('click', function () {
        let title = document.querySelector('#edit_noticeTitle').value
        let content = $('#edit_noticeContent').val()
        let deliverTime = new Date()
        deliverTime =
        deliverTime.getFullYear() +
          '-' +
          parseInt(deliverTime.getMonth() + 1) +
          '-' +
          deliverTime.getDate()
        $.ajax({
          type: 'POST',
          url: '../project/notice',
          dataType: 'json',
          data: {
            action,
            notice,
            id: noticeCURD.user_id,
            role: noticeCURD.user_role,
            title,
            content,
            deliverTime,
          },
          success: function (response) {
            alert('通知信息修改成功')
            window.location.reload()
          },
          error: function () {
            alert('修改失败，请重试！！！')
          },
        })
      })
  },

  // 增加通知信息
  addNoticeInfo() {
    let action = 'add'
    document
      .querySelector('#datatable_notice_add_button')
      .addEventListener('click', function () {
        $('#notice_add_form').modal('show')
        document.querySelector('#add_noticeTitle').value = ''
        document.querySelector('#add_noticeContent').innerHTML= ''
      })
    document
      .querySelector('#add_submit_button')
      .addEventListener('click', function () {
        let title = document.querySelector('#add_noticeTitle').value
        let content = $('#add_noticeContent').val()
        console.log(content);
        let deliverTime = new Date()
        deliverTime =
        deliverTime.getFullYear() +
          '-' +
          parseInt(deliverTime.getMonth() + 1) +
          '-' +
          deliverTime.getDate()
        $.ajax({
          type: 'POST',
          url: '../project/notice',
          data: {
            action,
            role:noticeCURD.user_role,
            id: noticeCURD.user_id,
            title,
            content,
            deliverTime,
          },
          success: function (response) {
            alert('通知信息添加成功')
            window.location.reload()
          },
          error: function () {
            alert('添加失败，请重试！！！')
          },
        })
      })
  },

  // 导出通知信息
  exportNoticeInfo() {
    document
      .querySelector('#datatable_notice_export_button')
      .addEventListener('click', function () {
        let dataObj = {}
        let title = []
        let notice = []
        var data = $('.datatable')
          .DataTable()
          .rows({ filter: 'applied' })
          .data()
        for (let i = 0; i < data.length; i++) {
          notice.push(data[i])
        }
        //添加表头
      
        title.push('id')
        title.push('publisherName')
        title.push('title')
        title.push('content')
        title.push('time')

        dataObj.TableTitle = title
        dataObj.TableList = notice

        $.ajax({
          async: false,
          type: 'post',
          url: '../project/exportNotice',
          contentType: 'application/json',
          dataType: 'json',
          data: JSON.stringify(dataObj),
          success: function (response) {
            document.getElementById('download_url').href = response.url
          },
          error: function () {
            alert('服务器错误')
          },
        })

        $('#notice_export_form').modal('show')
      })
  },

  //打印通知信息
  printNoticeInfo() {
    document
      .getElementById('datatable_notice_print_button')
      .addEventListener('click', function () {
        let noticeObj = {}
        let noticeList = []
        var data = $('.datatable')
          .DataTable()
          .rows({ filter: 'applied' })
          .data()
        for (let i = 0; i < data.length; i++) {
          noticeList.push(data[i])
        }
        noticeObj.noticeList = noticeList
        sessionStorage.setItem('noticeObj', JSON.stringify(noticeObj))
        window.open('./printPublish.html', '_blank')
      })
  },

  //统计通知信息
  staticNoticeInfo() {
    document
      .getElementById('datatable_notice_static_button')
      .addEventListener('click', function () {
        let noticeObj = {}
        let noticeList = []
        var data = $('.datatable')
          .DataTable()
          .rows({ filter: 'applied' })
          .data()
        for (let i = 0; i < data.length; i++) {
          noticeList.push(data[i])
        }
        noticeObj.noticeList = noticeList
        sessionStorage.setItem('noticeObj', JSON.stringify(noticeObj))
        window.open('./staticPublish.html', '_blank')
      })
  },

  init() {
    this.showPage()
    this.showDataTable()
    this.addNoticeInfo()
    this.exportNoticeInfo()
    this.printNoticeInfo()
    this.staticNoticeInfo()
  },
}

noticeCURD.init()
